import { Tree, INodeStruct, flatTree, findRoot, findParent } from 'spd-components/tree';
import { IEnterpriseStruct } from 'spd-request/organization-unit';
import { useState, useEffect, useImperativeHandle, forwardRef, ForwardedRef } from 'react';
import { Container } from 'spd-components/lazy-out/container';
import { AddButton } from 'spd-components/buttons';
import { useGetTreeList, createTree } from './use-tree-list';
import { INodeRef } from './defined';
import { EnterpriseForm } from '../enterprise-form';
import { message } from 'antd';
import { FormOutlined, DeleteOutlined } from '@ant-design/icons';
import './organization.less';
export type OrganizationTreeProps = { onActiveNodeChange?: (data: IEnterpriseStruct, node: any) => void, onDataChcange?: () => void };
type EnterpriceNode = INodeStruct<IEnterpriseStruct>;
// function useAddDepartment(activeNode: EnterpriceNode|null) {
//     let [visual, setVisual] = useState<boolean>(false);

// }
export const OrganizationTree = forwardRef((props: OrganizationTreeProps, ref: ForwardedRef<INodeRef>) => {
    const [tree, setTree, originData] = useGetTreeList();
    const [activeNode, setActiveNode] = useState<null | EnterpriceNode>(null);
    const [addFormVisual, setAddFormVisual] = useState<boolean>(false);
    // const [editFormVisual, setEditFormVisual] = useState<boolean>(false);
    const [editData, setEditData] = useState<any>(null);
    const [activeNodeRootId, setActiveNodeRoot] = useState<string>('');
    // const [ parentId, setParentId] = useState<number>(0);
    const companyTreeRightComponent = (
        <div className="container-header-right" key="2">
            <AddButton name="添加部门" onclick={() => {
                if (activeNode == null) {
                    return message.error('请选择上级部门！')
                }
                if (activeNode !== null) {
                    let activeRootNode = findRoot<IEnterpriseStruct>(tree, activeNode);
                    activeRootNode && setActiveNodeRoot(activeRootNode?.data.primaryId);
                    // for(let child of tree) {
                    //     // if(child.data.displayName != '筑智建重庆') continue;
                    //     let parent = findParent<IEnterpriseStruct>(child, activeNode);
                    //     if(parent != null) {
                    //         setParentId(parent.data.id);
                    //     }
                    // }
                }
                setAddFormVisual(true);
            }} />
        </div>
    );

    // 初始化
    useEffect(() => {
        setTree();
    }, []);

    useImperativeHandle(ref, () => ({
        getTreeData: () => tree,
        getOriginData: () => originData,
        getActiveNode: () => activeNode
    }));

    useEffect(() => {
        props.onDataChcange && props.onDataChcange();
    }, [originData, activeNode]);

    function onNodeClick(data: IEnterpriseStruct, node: EnterpriceNode) {
        if (activeNode == node) {
            setActiveNode(null);
            node.isActive = false;
        } else {
            let flatdata = flatTree(tree);
            flatdata.forEach(item => item.isActive = false);
            node.isActive = true;
            setActiveNode(node);
        }
    }

    const EnterpriseFormAdd = (
        <EnterpriseForm.Add
            onCancel={() => setAddFormVisual(false)}
            department={activeNode?.data}
            rootEnterpriceId={activeNodeRootId}
            onSuccessAdd={(data) => {
                let newNode = createTree(activeNode?.data.id, [data]);
                activeNode?.children.push(...newNode);
                setTree(false);
                setAddFormVisual(false);
            }}
        />
    );
    const EnterpriceFormEdit = (
        <EnterpriseForm.Edit
            onCancel={() => setEditData(null)}
            department={activeNode?.data}
            rootEnterpriceId={activeNodeRootId}
            originData={editData}
            onSuccessAdd={(data) => {
                editData.displayName = data.displayName;
                setTree(false);
                setEditData(null);
            }}
        />
    );
    return (
        <>
            <Container title="企业列表" rightContent={[companyTreeRightComponent]}>
                <div className="tree-content">
                    <Tree.Context.Provider value={{ onNodeClick: onNodeClick, dataChange: () => { } }}>
                        <Tree.Node datas={tree} className="tree-item" renderChildren={(node) => {
                            return (
                                <div className="tree-item-operate">
                                    <FormOutlined onClick={() => {
                                        setEditData(node.data)
                                    }} />
                                    &nbsp;&nbsp;
                                    <DeleteOutlined />
                                </div>
                            )
                        }} />
                    </Tree.Context.Provider>
                </div>
            </Container>
            {addFormVisual ? EnterpriseFormAdd : ''}
            {editData ? EnterpriceFormEdit : ''}
        </>
    );
});